package com.monitoringfloty.androidclient;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;


public class positionUpdater implements SettingsListener {
 
    private static volatile positionUpdater instance = null;
	private SettingsSingleton settings;
    private Socket sock;
    private BufferedReader buffreader;
    private BufferedWriter buffwriter;
    private String deviceID;
    private String srvIP;
    private boolean connected=false;
    private Context cntx;
    
 
    public static positionUpdater getInstance() {
        if (instance == null) {
            synchronized (positionUpdater.class) {
                if (instance == null) {
                    instance = new positionUpdater();
                }
            }
        }
        return instance;
    }
 
    private positionUpdater() {
    	settings = SettingsSingleton.getInstance();
    	deviceID = settings.getString("DeviceID", "AndroidClient");
    	srvIP = settings.getString("ServerIP", "192.168.0.30");
    	settings.addListener(this);
    	connect();
    }
    
    private boolean checkConnectivity() {
    	if(cntx!=null) {
    		ConnectivityManager connectivityManager = (ConnectivityManager)cntx.getSystemService(Context.CONNECTIVITY_SERVICE);
    		NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    	}
    	return false;
    }
    
    public void setContext(Context context) {
    	cntx=context;
    }
    
    public boolean connect() {
    	if(!checkConnectivity()) {
    		return false;
    	}
    	try {
            sock = new Socket();
            sock.connect( new InetSocketAddress( srvIP, 2055 ), 1000 );
            buffreader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            buffwriter = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
            connected=true;
            return true;
    	}
    	catch (UnknownHostException e) {
    		connected=false;
    		return false;
    	}
    	catch (IOException e) {
    		connected=false;
    		return false;
    	}
    }
    
    public String SendPos(double lat, double lon) {	
    	Log.i("INFO", "Sending pos:"+lat+" "+lon);
    	if(!checkConnectivity()) 
    		return "No internet connection avaliable";
    	try {
    		if(!connected)
    			this.connect();
    		if(sock.isConnected()) {
    			buffwriter.write(generateReport(lat,lon));
    	    	buffwriter.flush();	
    	    	connected=true;
    	    	return "Success";
    		}
    		else {
    			connected=false;
    			return "No server available!";
    		}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace(;
			connected=false;
			SendPos(lat,lon);
		}
		return "Success";
    }
    
    public void close() {
    	if(sock!=null)
			try {
				sock.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    }
    
    public String generateReport(double lat, double lon) {
    	String latS = ""+lat;
    	String lonS = ""+lon;
    	latS=latS.replace(".", ",");
    	lonS=lonS.replace(".",",");
    	String s = "<MobilePositionReport><DeviceID>"+deviceID+"</DeviceID><Latitude>"+latS+"</Latitude><Longtitude>"+lonS+"</Longtitude></MobilePositionReport>\n";
    	return s;
    }

	@Override
	public void onSettingsUpdate(int[] wyniki) {
		// TODO Auto-generated method stub
		String changedIP = settings.getString("ServerIP", "192.168.0.30"); 
		String changedID = settings.getString("DeviceID", "AndroidClient"); 
		if(srvIP.compareToIgnoreCase(changedIP)!=0){
			close();
			srvIP=changedIP;
			connect();
		}
		if(deviceID.compareTo(changedID)!=0) {
			deviceID=changedID;
		}
	}
 
}

